<template>
  <ex-dialog v-model="visible" @close="closePosition" draggable :title="form.positionName ? form.positionName : (form.id ? form.positionName : '新增')"
  width="700" :contentHeight="450">
  <template #default>
      <el-tabs v-model="activeName"  style="height: 100%;">
        <el-tab-pane label="基本信息" name="base" style="height: 100%;">
          <el-row :gutter="80">
            <el-col :lg="24">
              <el-form :model="form" :rules="button_rules" ref="dialogForm" label-width="80px" label-position="left">
<!--                <el-form-item label="位置编码" prop="positionCode">-->
<!--                  <el-input v-model="form.positionCode" clearable placeholder="位置编码"></el-input>-->
<!--                </el-form-item>-->

                <el-form-item label="位置名称" prop="positionName">
                  <el-input v-model="form.positionName" clearable placeholder="位置名称"></el-input>
                </el-form-item>
                <el-form-item label="上级位置" prop="parentLevelCode">
                  <ex-cascader v-model="form.parentLevelCode" dict-code="FamsPosition" key-prop="levelCode" placeholder="默认所有"></ex-cascader>
<!--                  <el-cascader v-model="form.parentLevelCode" :options="positionOptions" :props="positionProps"-->
<!--                               :show-all-levels="false" placeholder="默认所有" clearable></el-cascader>-->
                </el-form-item>
                <el-form-item label="排序" prop="orderWeight">
                <el-input v-model="form.orderWeight" clearable placeholder="排序"></el-input>
                </el-form-item>
              </el-form>

            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="关联部门" name="SysRole" style="height: 100%">
          <ex-rel-table ref="deptRelTable" size="small" :rel-entity="form" :treeApi="this.$API.system.dept.treeData" default-expand-all>
            提示: 默认所有部门不可用，若勾选之后，则只有勾选部门可用
          </ex-rel-table>
        </el-tab-pane>
      </el-tabs>
    </template>
    <template #footer>
      <div style="flex: auto;text-align: center">
        <el-button plain type="primary" @click="save" :loading="loading">保 存</el-button>
        <el-button plain type="warning" @click="reset" :loading="loading">重 置</el-button>
        <el-button plain type="info" @click="closePosition" :loading="loading">关 闭</el-button>
      </div>
    </template>

  </ex-dialog>
</template>

<script>
import scIconSelect from '@/components/scIconSelect'
import ExRelTable from "@/components/exRelTable/index.vue";
import ExCascader from "@/components/exCascader/index.vue";
import exDialog from '@/components/exDialog';
import BaseTemplate from "@/utils/baseTemplate";

export default {
  computed: {
  },
  emits: ['success'],
  components: {
    ExCascader,
    ExRelTable,
    scIconSelect,
    exDialog
  },
  props: {
    menu: {
      type: Object, default: () => {
      }
    },
  },
  data() {
    return {
      activeName: 'base',
      visible: false,
      form: {
        id: "",
        positionCode: "",
        positionName: "",
        positionAddress: "",
        parentLevelCode:""
      },
      positionOptions: [],
      positionProps: {
        value: 'levelCode',
        label: 'label',
        checkStrictly: true,
        emitPath:false,
      },
      button_rules: {
        positionName: [
          {required: true, message: "请输入位置名称", trigger: "blur"},
        ],
      },
      loading: false,
      oldForm: null,
    }
  },
  watch: {},
  mounted() {
  },
  onLoad() {
  },
  methods: {
    //显示
    open(entity) {
		this.form = {};
		this.oldForm = {};
		if(!entity.other){
			entity.other = {}
		}
		console.log(this.form)
		this.form = Object.assign({}, entity);
      	this.oldForm = Object.assign({}, this.form);
      	this.visible = true;
      	this.activeName = "base";
      	// this.loadtree();
    },
	  closePosition() {
		  this.reset();
		  this.visible = false;
	  },
    reset() {
      this.form = Object.assign({}, this.oldForm);
		for(let ref in this.$refs){
			try {
				this.$refs[ref].refresh();
			}catch (e){
			}
		}
    },
    async loadtree() {
		this.positionOptions = await this.$cache.tree.reload(this.$API.system.position.treeData.storeName, {});
		this.addDisabled(this.positionOptions);
    },
    addDisabled(datas){
      datas.forEach(item=>{

        item.disabled = item.isEnabled !== '1';
        if(item.children){
          this.addDisabled(item.children);
        }
      })
    },
    //保存
    async save() {
      let valid = await BaseTemplate.validate(this,this.$refs.dialogForm);
      if (valid) {
		  this.loading = true;
		  let queryParams = {};
		  queryParams.levelCode = this.form.parentLevelCode;
		  let parentPositionAddress = "";
		  let levelNumber = 1;
		  if(this.form.parentLevelCode){
			  let rsp = await this.$API.system.position.findOne.post(queryParams);
			  if(rsp.code === 2000){
				  if(rsp.data){
					  parentPositionAddress = rsp.data.positionAddress;
					  levelNumber = rsp.data.pathCode.split(",").length;
				  }
				  if(rsp.data && rsp.data.other && rsp.data.other.positionType){
					  this.loading = false;
					  this.$message.warning("该位置只能挂载在区级以上，请选择其他上级菜单");
					  return;
				  }
			  }else {
				  this.loading = false;
				  this.$message.warning("数据加载失败，请稍后重新");
				  return;
			  }
		  }
		  if(parentPositionAddress){
			  this.form.positionAddress = parentPositionAddress+"/"+this.form.positionName;
		  }else{
			  this.form.positionAddress = this.form.positionName;
		  }
		  if(levelNumber === 3){
			  this.form.other.isNotAction = "0";
			  this.form.other.isCanCreate = "1";
			  this.form.other.positionType = "1";
		  }else{
			  this.form.other.isNotAction = "1";
			  this.form.other.isCanCreate = "0";
		  }
		  //验证名称是否重复(9.6号更新)
		  // let queryParam = {};
		  // queryParam.positionName = this.form.positionName;
		  // if(this.form.parentLevelCode){
			//   queryParam.parentLevelCode = this.form.parentLevelCode;
		  // }else {
			//   queryParam.parentLevelCode = '0000000';
		  // }
		  // let checkRes = await this.$API.system.position.listData.post(queryParam);
		  // if (checkRes.code === 2000) {
		  // 	if(checkRes.data.length > 0){
		  // 		if (!this.form.id) {
		  // 			this.$message.warning("该位置名称已存在,请输入其他名称");
		  // 			return;
		  // 		}else{
		  // 			if(this.oldForm.parentLevelCode !== this.form.parentLevelCode){
		  // 				this.$message.warning("您选择的父节点下有相同名称位置，请修改位置名称");
		  // 				return;
		  // 			}else {
		  // 				this.$message.warning("该位置名称已存在,请输入其他名称");
		  // 				return;
		  // 			}
		  // 		}
		  //
		  // 	}
		  // }else {
		  // 	this.$message.warning("请重新尝试");
		  // 	return;
		  // }
		  try {
			  let res;
			  if (this.form.id) {
				  res = await this.$API.system.position.updatePosition.post(this.form)
			  } else {
				  if(!this.form.parentLevelCode){
					  this.form.parentLevelCode = '0000000';
				  }
				  res = await this.$API.system.position.add.post(this.form)
			  }
			  if (res.code === 2000) {

				  this.$message.success(this.$t("code."+res.code));
				  this.$emit('success');
				  this.visible = false;
				  this.$store.dispatch("commit",this.form.entityName);
			  } else {
				  this.$message.warning(res.message)
			  }
		  } finally {
			  this.loading = false;
		  }
      }
    },
  }
}
</script>

<style scoped>
h2 {
  font-size: 17px;
  color: #3c4a54;
  padding: 0 0 30px 0;
}

[data-theme="dark"] h2 {
  color: #fff;
}

</style>
